import { useMemo } from "react"
import { useLocation } from "react-router-dom"
//这个hook用于操作本地存储

type methods = {
    set: (value: any) => void
    rm: () => void
}
//key 存储到本地存储的key

//value 存储到本地的值

/**
 * @param storageType 存储类型
 */

//重新声明全局window索引签名
declare global {
    interface Window {
        [k: string]: any
    }
}

type Istorage = (key: string, storageType?: string) => [string | null, methods]

const useStorage: Istorage = (key, storageType = 'localStorage') => {
    let location = useLocation()
    //使用useMemo从本地取出结果
    let localVal = useMemo<string | null>(() => {
        let valueRes: string | null;
        try {
            //从本地获取
            valueRes = window[storageType].getItem(key)
            valueRes = valueRes ? JSON.parse(valueRes!) : null
            return valueRes
        } catch (e: any) {
            console.log(e.toString())
            return null
        }
    }, [location])

    //存到本地
    // window[storageType].setItem()
    //移除
    let methodObj: methods = {
        //设定缓存
        set: (value: any) => {
            let valueJson;
            try {
                valueJson = JSON.stringify(value!)
                window[storageType].setItem(key, valueJson!)
            } catch (e: any) {
                console.log(e.toString())
            }
        },
        //移除缓存
        rm: () => {
            window[storageType].removeItem(key)
        }
    }

    return [localVal, methodObj]
}

export default useStorage